{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d983a474",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/retrievers/auto_vs_recursive_retriever.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fa01d8c-261f-4da2-8698-5eae785e2f81",
   "metadata": {},
   "source": [
    "# Comparing Methods for Structured Retrieval (Auto-Retrieval vs. Recursive Retrieval)\n",
    "\n",
    "In a naive RAG system, the set of input documents are then chunked, embedded, and dumped to a vector database collection. Retrieval would just fetch the top-k documents by embedding similarity.\n",
    "\n",
    "This can fail if the set of documents is large - it can be hard to disambiguate raw chunks, and you're not guaranteed to filter for the set of documents that contain relevant context.\n",
    "\n",
    "In this guide we explore **structured retrieval** - more advanced query algorithms that take advantage of structure within your documents for higher-precision retrieval. We compare the following two methods:\n",
    "\n",
    "- **Metadata Filters + Auto-Retrieval**: Tag each document with the right set of metadata. During query-time, use auto-retrieval to infer metadata filters along with passing through the query string for semantic search.\n",
    "- **Store Document Hierarchies (summaries -> raw chunks) + Recursive Retrieval**: Embed document summaries and map that to the set of raw chunks for each document. During query-time, do recursive retrieval to first fetch summaries before fetching documents."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "157674b5",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a264ff0",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-openai\n",
    "%pip install llama-index-vector-stores-weaviate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d04a05c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15c61ad0-25e3-4a07-a5af-d604f36b84aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d38e8cbf-53da-4fed-8770-860e9e83d329",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import sys\n",
    "from llama_index.core import SimpleDirectoryReader\n",
    "from llama_index.core import SummaryIndex\n",
    "\n",
    "logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n",
    "logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9107ed7c-9727-40c9-ae43-862a8c67b7d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "wiki_titles = [\"Michael Jordan\", \"Elon Musk\", \"Richard Branson\", \"Rihanna\"]\n",
    "wiki_metadatas = {\n",
    "    \"Michael Jordan\": {\n",
    "        \"category\": \"Sports\",\n",
    "        \"country\": \"United States\",\n",
    "    },\n",
    "    \"Elon Musk\": {\n",
    "        \"category\": \"Business\",\n",
    "        \"country\": \"United States\",\n",
    "    },\n",
    "    \"Richard Branson\": {\n",
    "        \"category\": \"Business\",\n",
    "        \"country\": \"UK\",\n",
    "    },\n",
    "    \"Rihanna\": {\n",
    "        \"category\": \"Music\",\n",
    "        \"country\": \"Barbados\",\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec14903c-9e13-4a41-a8e0-f8bf9e0b5c89",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "import requests\n",
    "\n",
    "for title in wiki_titles:\n",
    "    response = requests.get(\n",
    "        \"https://en.wikipedia.org/w/api.php\",\n",
    "        params={\n",
    "            \"action\": \"query\",\n",
    "            \"format\": \"json\",\n",
    "            \"titles\": title,\n",
    "            \"prop\": \"extracts\",\n",
    "            # 'exintro': True,\n",
    "            \"explaintext\": True,\n",
    "        },\n",
    "    ).json()\n",
    "    page = next(iter(response[\"query\"][\"pages\"].values()))\n",
    "    wiki_text = page[\"extract\"]\n",
    "\n",
    "    data_path = Path(\"data\")\n",
    "    if not data_path.exists():\n",
    "        Path.mkdir(data_path)\n",
    "\n",
    "    with open(data_path / f\"{title}.txt\", \"w\") as fp:\n",
    "        fp.write(wiki_text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cee3a660-dfff-4865-8fe8-75862a2b4c78",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load all wiki documents\n",
    "docs_dict = {}\n",
    "for wiki_title in wiki_titles:\n",
    "    doc = SimpleDirectoryReader(\n",
    "        input_files=[f\"data/{wiki_title}.txt\"]\n",
    "    ).load_data()[0]\n",
    "\n",
    "    doc.metadata.update(wiki_metadatas[wiki_title])\n",
    "    docs_dict[wiki_title] = doc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "438b87ce-729d-4fad-9464-b9fa30e069b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.core.callbacks import LlamaDebugHandler, CallbackManager\n",
    "from llama_index.core.node_parser import SentenceSplitter\n",
    "\n",
    "\n",
    "llm = OpenAI(\"gpt-4\")\n",
    "callback_manager = CallbackManager([LlamaDebugHandler()])\n",
    "splitter = SentenceSplitter(chunk_size=256)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c07f3302-f0c1-485e-990e-ac6b1dda2577",
   "metadata": {},
   "source": [
    "## Metadata Filters + Auto-Retrieval\n",
    "\n",
    "In this approach, we tag each Document with metadata (category, country), and store in a Weaviate vector db.\n",
    "\n",
    "During retrieval-time, we then perform \"auto-retrieval\" to infer the relevant set of metadata filters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3a35007-9bd0-42cc-be52-ba0316f80635",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Setup Weaviate\n",
    "import weaviate\n",
    "\n",
    "# cloud\n",
    "auth_config = weaviate.AuthApiKey(api_key=\"<api_key>\")\n",
    "client = weaviate.Client(\n",
    "    \"https://llama-index-test-v0oggsoz.weaviate.network\",\n",
    "    auth_client_secret=auth_config,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7051c353-ba65-4a47-bf9a-f5b97d7212ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import VectorStoreIndex, SimpleDirectoryReader\n",
    "from llama_index.vector_stores.weaviate import WeaviateVectorStore\n",
    "from IPython.display import Markdown, display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c2dcf5d-f539-4e83-8017-0a79ef398132",
   "metadata": {},
   "outputs": [],
   "source": [
    "# drop items from collection first\n",
    "client.schema.delete_class(\"LlamaIndex\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2f0e889-1f16-4660-863c-dca8ef63fbe0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import StorageContext\n",
    "\n",
    "# If you want to load the index later, be sure to give it a name!\n",
    "vector_store = WeaviateVectorStore(\n",
    "    weaviate_client=client, index_name=\"LlamaIndex\"\n",
    ")\n",
    "storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "\n",
    "# NOTE: you may also choose to define a index_name manually.\n",
    "# index_name = \"test_prefix\"\n",
    "# vector_store = WeaviateVectorStore(weaviate_client=client, index_name=index_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d01b32c2-5625-4b6f-87eb-198b5f3f37da",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'class': 'LlamaIndex',\n",
       " 'description': 'Class for LlamaIndex',\n",
       " 'invertedIndexConfig': {'bm25': {'b': 0.75, 'k1': 1.2},\n",
       "  'cleanupIntervalSeconds': 60,\n",
       "  'stopwords': {'additions': None, 'preset': 'en', 'removals': None}},\n",
       " 'multiTenancyConfig': {'enabled': False},\n",
       " 'properties': [{'dataType': ['text'],\n",
       "   'description': 'Text property',\n",
       "   'indexFilterable': True,\n",
       "   'indexSearchable': True,\n",
       "   'name': 'text',\n",
       "   'tokenization': 'word'},\n",
       "  {'dataType': ['text'],\n",
       "   'description': 'The ref_doc_id of the Node',\n",
       "   'indexFilterable': True,\n",
       "   'indexSearchable': True,\n",
       "   'name': 'ref_doc_id',\n",
       "   'tokenization': 'word'},\n",
       "  {'dataType': ['text'],\n",
       "   'description': 'node_info (in JSON)',\n",
       "   'indexFilterable': True,\n",
       "   'indexSearchable': True,\n",
       "   'name': 'node_info',\n",
       "   'tokenization': 'word'},\n",
       "  {'dataType': ['text'],\n",
       "   'description': 'The relationships of the node (in JSON)',\n",
       "   'indexFilterable': True,\n",
       "   'indexSearchable': True,\n",
       "   'name': 'relationships',\n",
       "   'tokenization': 'word'}],\n",
       " 'replicationConfig': {'factor': 1},\n",
       " 'shardingConfig': {'virtualPerPhysical': 128,\n",
       "  'desiredCount': 1,\n",
       "  'actualCount': 1,\n",
       "  'desiredVirtualCount': 128,\n",
       "  'actualVirtualCount': 128,\n",
       "  'key': '_id',\n",
       "  'strategy': 'hash',\n",
       "  'function': 'murmur3'},\n",
       " 'vectorIndexConfig': {'skip': False,\n",
       "  'cleanupIntervalSeconds': 300,\n",
       "  'maxConnections': 64,\n",
       "  'efConstruction': 128,\n",
       "  'ef': -1,\n",
       "  'dynamicEfMin': 100,\n",
       "  'dynamicEfMax': 500,\n",
       "  'dynamicEfFactor': 8,\n",
       "  'vectorCacheMaxObjects': 1000000000000,\n",
       "  'flatSearchCutoff': 40000,\n",
       "  'distance': 'cosine',\n",
       "  'pq': {'enabled': False,\n",
       "   'bitCompression': False,\n",
       "   'segments': 0,\n",
       "   'centroids': 256,\n",
       "   'trainingLimit': 100000,\n",
       "   'encoder': {'type': 'kmeans', 'distribution': 'log-normal'}}},\n",
       " 'vectorIndexType': 'hnsw',\n",
       " 'vectorizer': 'none'}"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# validate that the schema was created\n",
    "class_schema = client.schema.get(\"LlamaIndex\")\n",
    "display(class_schema)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fce23e0-0632-4c72-97d3-e2c845e32555",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "**********\n",
      "Trace: index_construction\n",
      "**********\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: insert\n",
      "**********\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: insert\n",
      "**********\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: insert\n",
      "**********\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: insert\n",
      "**********\n"
     ]
    }
   ],
   "source": [
    "index = VectorStoreIndex(\n",
    "    [],\n",
    "    storage_context=storage_context,\n",
    "    transformations=[splitter],\n",
    "    callback_manager=callback_manager,\n",
    ")\n",
    "\n",
    "# add documents to index\n",
    "for wiki_title in wiki_titles:\n",
    "    index.insert(docs_dict[wiki_title])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40f0717a-c868-4570-a8c6-57e3f50ce819",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.retrievers import VectorIndexAutoRetriever\n",
    "from llama_index.core.vector_stores.types import MetadataInfo, VectorStoreInfo\n",
    "\n",
    "\n",
    "vector_store_info = VectorStoreInfo(\n",
    "    content_info=\"brief biography of celebrities\",\n",
    "    metadata_info=[\n",
    "        MetadataInfo(\n",
    "            name=\"category\",\n",
    "            type=\"str\",\n",
    "            description=(\n",
    "                \"Category of the celebrity, one of [Sports, Entertainment,\"\n",
    "                \" Business, Music]\"\n",
    "            ),\n",
    "        ),\n",
    "        MetadataInfo(\n",
    "            name=\"country\",\n",
    "            type=\"str\",\n",
    "            description=(\n",
    "                \"Country of the celebrity, one of [United States, Barbados,\"\n",
    "                \" Portugal]\"\n",
    "            ),\n",
    "        ),\n",
    "    ],\n",
    ")\n",
    "retriever = VectorIndexAutoRetriever(\n",
    "    index,\n",
    "    vector_store_info=vector_store_info,\n",
    "    llm=llm,\n",
    "    callback_manager=callback_manager,\n",
    "    max_top_k=10000,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "249a8a74-5bde-4b42-9b43-62764484158b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using query str: Tell me about a celebrity\n",
      "Using query str: Tell me about a celebrity\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using filters: [('country', '==', 'United States')]\n",
      "Using filters: [('country', '==', 'United States')]\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using top_k: 2\n",
      "Using top_k: 2\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: query\n",
      "    |_retrieve ->  4.232108 seconds\n",
      "**********\n"
     ]
    }
   ],
   "source": [
    "# NOTE: the \"set top-k to 10000\" is a hack to return all data.\n",
    "# Right now auto-retrieval will always return a fixed top-k, there's a TODO to allow it to be None\n",
    "# to fetch all data.\n",
    "# So it's theoretically possible to have the LLM infer a None top-k value.\n",
    "nodes = retriever.retrieve(\n",
    "    \"Tell me about a celebrity from the United States, set top k to 10000\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56408d2f-f532-4010-bf81-7a8487433f9e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of nodes: 2\n",
      "In December 2023, Judge Laurel Beeler ruled that Musk must testify again for the SEC.  \n",
      "\n",
      "\n",
      "== Public perception ==\n",
      "\n",
      "Though his ventures were influential within their own industries in the 2000s, Musk only became a public figure in the early 2010s. He has been described as an eccentric who makes spontaneous and controversial statements, contrary to other billionaires who prefer reclusiveness to protect their businesses. Vance described people's opinions of Musk as polarized due to his \"part philosopher, part troll\" role on Twitter.Musk was a partial inspiration for the characterization of Tony Stark in the Marvel film Iron Man (2008). Musk also had a cameo appearance in the film's 2010 sequel, Iron Man 2. Musk has made cameos and appearances in other films such as Machete Kills (2013), Why Him? (2016), and Men in Black: International (2019). Television series in which he has appeared include The Simpsons (\"The Musk Who Fell to Earth\", 2015), The Big Bang Theory (\"The Platonic Permutation\", 2015), South Park (\"Members Only\", 2016), Young Sheldon (\"A Patch, a Modem, and a Zantac®\", 2017), Rick and Morty (\"One Crew over the Crewcoo's Morty\", 2019), and Saturday Night Live (2021).\n",
      "Musk also had a cameo appearance in the film's 2010 sequel, Iron Man 2. Musk has made cameos and appearances in other films such as Machete Kills (2013), Why Him? (2016), and Men in Black: International (2019). Television series in which he has appeared include The Simpsons (\"The Musk Who Fell to Earth\", 2015), The Big Bang Theory (\"The Platonic Permutation\", 2015), South Park (\"Members Only\", 2016), Young Sheldon (\"A Patch, a Modem, and a Zantac®\", 2017), Rick and Morty (\"One Crew over the Crewcoo's Morty\", 2019), and Saturday Night Live (2021). He contributed interviews to the documentaries Racing Extinction (2015) and the Werner Herzog-directed Lo and Behold (2016).Musk was elected a Fellow of the Royal Society (FRS) in 2018. In 2015, he received an honorary doctorate in engineering and technology from Yale University and IEEE Honorary Membership.\n"
     ]
    }
   ],
   "source": [
    "print(f\"Number of nodes: {len(nodes)}\")\n",
    "for node in nodes[:10]:\n",
    "    print(node.node.get_content())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ead6887-18c4-4855-8152-9b99016d4618",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using query str: childhood of a popular sports celebrity\n",
      "Using query str: childhood of a popular sports celebrity\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using filters: [('category', '==', 'Sports'), ('country', '==', 'United States')]\n",
      "Using filters: [('category', '==', 'Sports'), ('country', '==', 'United States')]\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using top_k: 2\n",
      "Using top_k: 2\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: query\n",
      "    |_retrieve ->  3.546065 seconds\n",
      "**********\n",
      "It was announced on November 30, 2013, that the two were expecting their first child together. On February 11, 2014, Prieto gave birth to identical twin daughters named Victoria and Ysabel. In 2019, Jordan became a grandfather when his daughter Jasmine gave birth to a son, whose father is professional basketball player Rakeem Christmas.\n",
      "\n",
      "\n",
      "== Media figure and business interests ==\n",
      "\n",
      "\n",
      "=== Endorsements ===\n",
      "Jordan is one of the most marketed sports figures in history. He has been a major spokesman for such brands as Nike, Coca-Cola, Chevrolet, Gatorade, McDonald's, Ball Park Franks, Rayovac, Wheaties, Hanes, and MCI. Jordan has had a long relationship with Gatorade, appearing in over 20 commercials for the company since 1991, including the \"Be Like Mike\" commercials in which a song was sung by children wishing to be like Jordan.Nike created a signature shoe for Jordan, called the Air Jordan, in 1984. One of Jordan's more popular commercials for the shoe involved Spike Lee playing the part of Mars Blackmon.\n",
      "In 2019, Jordan became a grandfather when his daughter Jasmine gave birth to a son, whose father is professional basketball player Rakeem Christmas.\n",
      "\n",
      "\n",
      "== Media figure and business interests ==\n",
      "\n",
      "\n",
      "=== Endorsements ===\n",
      "Jordan is one of the most marketed sports figures in history. He has been a major spokesman for such brands as Nike, Coca-Cola, Chevrolet, Gatorade, McDonald's, Ball Park Franks, Rayovac, Wheaties, Hanes, and MCI. Jordan has had a long relationship with Gatorade, appearing in over 20 commercials for the company since 1991, including the \"Be Like Mike\" commercials in which a song was sung by children wishing to be like Jordan.Nike created a signature shoe for Jordan, called the Air Jordan, in 1984. One of Jordan's more popular commercials for the shoe involved Spike Lee playing the part of Mars Blackmon. In the commercials, Lee, as Blackmon, attempted to find the source of Jordan's abilities and became convinced that \"it's gotta be the shoes\".\n"
     ]
    }
   ],
   "source": [
    "nodes = retriever.retrieve(\n",
    "    \"Tell me about the childhood of a popular sports celebrity in the United\"\n",
    "    \" States\"\n",
    ")\n",
    "for node in nodes:\n",
    "    print(node.node.get_content())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0a8627c-662f-47b9-8e48-7c2f237dda1a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using query str: college life of a billionaire who started at company at the age of 16\n",
      "Using query str: college life of a billionaire who started at company at the age of 16\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using filters: []\n",
      "Using filters: []\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using top_k: 2\n",
      "Using top_k: 2\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: query\n",
      "    |_retrieve ->  2.60008 seconds\n",
      "**********\n",
      "After his parents divorced in 1980, Musk chose to live primarily with his father. Musk later regretted his decision and became estranged from his father. He has a paternal half-sister and a half-brother.In one incident, after having called a boy whose father had committed suicide \"stupid\", Musk was severely beaten and thrown down concrete steps. His father derided Elon for his behavior and showed no sympathy for him despite his injuries. He was also an enthusiastic reader of books, later attributing his success in part to having read Benjamin Franklin: An American Life, Lord of the Flies, the Foundation series, and The Hitchhiker's Guide to the Galaxy. At age ten, he developed an interest in computing and video games, teaching himself how to program from the VIC-20 user manual. At age twelve, Musk sold his BASIC-based game Blastar to PC and Office Technology magazine for approximately $500.\n",
      "\n",
      "\n",
      "=== Education ===\n",
      "Musk attended Waterkloof House Preparatory School, Bryanston High School, and then Pretoria Boys High School, where he graduated.\n",
      "He has a paternal half-sister and a half-brother.In one incident, after having called a boy whose father had committed suicide \"stupid\", Musk was severely beaten and thrown down concrete steps. His father derided Elon for his behavior and showed no sympathy for him despite his injuries. He was also an enthusiastic reader of books, later attributing his success in part to having read Benjamin Franklin: An American Life, Lord of the Flies, the Foundation series, and The Hitchhiker's Guide to the Galaxy. At age ten, he developed an interest in computing and video games, teaching himself how to program from the VIC-20 user manual. At age twelve, Musk sold his BASIC-based game Blastar to PC and Office Technology magazine for approximately $500.\n",
      "\n",
      "\n",
      "=== Education ===\n",
      "Musk attended Waterkloof House Preparatory School, Bryanston High School, and then Pretoria Boys High School, where he graduated. Musk was a good but not exceptional student, earning a 61 in Afrikaans and a B on his senior math certification.\n"
     ]
    }
   ],
   "source": [
    "nodes = retriever.retrieve(\n",
    "    \"Tell me about the college life of a billionaire who started at company at\"\n",
    "    \" the age of 16\"\n",
    ")\n",
    "for node in nodes:\n",
    "    print(node.node.get_content())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33425c39-e0e7-4415-b695-66c96d3fc7d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using query str: childhood of a UK billionaire\n",
      "Using query str: childhood of a UK billionaire\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using filters: [('category', '==', 'Business'), ('country', '==', 'United Kingdom')]\n",
      "Using filters: [('category', '==', 'Business'), ('country', '==', 'United Kingdom')]\n",
      "INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using top_k: 2\n",
      "Using top_k: 2\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: query\n",
      "    |_retrieve ->  3.565899 seconds\n",
      "**********\n"
     ]
    }
   ],
   "source": [
    "nodes = retriever.retrieve(\"Tell me about the childhood of a UK billionaire\")\n",
    "for node in nodes:\n",
    "    print(node.node.get_content())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45612783-c82c-48f7-ace9-d04341b9d3ec",
   "metadata": {},
   "source": [
    "## Build Recursive Retriever over Document Summaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a127983-f083-41d8-9299-e8f93e1ee112",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.schema import IndexNode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07d4509e-715c-4844-975b-db2afa900fe5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: index_construction\n",
      "**********\n",
      "**Summary for Michael Jordan: Michael Jordan, often referred to as MJ, is a retired professional basketball player from the United States who is widely considered one of the greatest players in the history of the sport. He played 15 seasons in the NBA, primarily with the Chicago Bulls, and won six NBA championships. His individual accolades include six NBA Finals MVP awards, ten NBA scoring titles, five NBA MVP awards, and fourteen NBA All-Star Game selections. He also holds the NBA records for career regular season scoring average and career playoff scoring average. Jordan briefly retired to play Minor League Baseball, but returned to lead the Bulls to three more championships. He was twice inducted into the Naismith Memorial Basketball Hall of Fame. \n",
      "\n",
      "After retiring, Jordan became a successful businessman, part-owner and head of basketball operations for the Charlotte Hornets, and owner of 23XI Racing in the NASCAR Cup Series. He has also made significant contributions to charitable causes, donating millions to organizations such as the Make-A-Wish Foundation and Habitat for Humanity. In the entertainment industry, he has appeared in productions like \"Space Jam\" and \"The Last Dance\", and has authored several books about his life and career. His influence extends beyond sports, making him a significant cultural figure.\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: index_construction\n",
      "**********\n",
      "**Summary for Elon Musk: Elon Musk is a globally recognized business magnate and investor, who has founded and led numerous high-profile technology companies. He is the founder, CEO, and chief technology officer of SpaceX, an aerospace manufacturer and space transportation company, and the CEO and product architect of Tesla, Inc., a company specializing in electric vehicles and clean energy. Musk also owns and chairs X Corp, and founded the Boring Company, a tunnel construction and infrastructure company. He co-founded Neuralink, a neurotechnology company, and OpenAI, a nonprofit artificial intelligence research company. \n",
      "\n",
      "In 2022, Musk acquired Twitter and merged it with X Corp, and also founded xAI, an AI company. Despite his success, he has faced criticism for his controversial statements and management style. Musk was born in South Africa, moved to Canada at 18, and later to the United States to attend Stanford University, but dropped out to start his entrepreneurial journey. He co-founded Zip2 and X.com (later PayPal), which was sold to eBay in 2002. \n",
      "\n",
      "Musk envisions a future that includes Mars colonization and the development of a high-speed transportation system known as the Hyperloop. As of August 2023, he is the wealthiest person in the world, with a net worth of over $200 billion. Despite various controversies, Musk has made significant contributions to the tech industry. He has been married multiple times, has several children, and is known for his active presence on social media, particularly Twitter.\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: index_construction\n",
      "**********\n",
      "**Summary for Richard Branson: Richard Branson, born on 18 July 1950, is a British business magnate, commercial astronaut, and philanthropist. He founded the Virgin Group in the 1970s, which now controls over 400 companies in various fields such as aviation, music, and space travel. His first business venture was a magazine called Student, and he later established a mail-order record business and a chain of record stores known as Virgin Records. The Virgin brand expanded rapidly during the 1980s with the start of Virgin Atlantic airline and the expansion of the Virgin Records music label. In 1997, he founded the Virgin Rail Group, and in 2004, he founded Virgin Galactic. Branson was knighted in 2000 for his services to entrepreneurship. He has a net worth of US$3 billion as of June 2023. Branson has also been involved in numerous philanthropic activities and has launched initiatives like Virgin Startup. Despite his success, he has faced criticism and legal issues, including a brief jail term for tax evasion in 1971. He is married to Joan Templeman, with whom he has two children.\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: index_construction\n",
      "**********\n",
      "**Summary for Rihanna: Rihanna, whose real name is Robyn Rihanna Fenty, is a renowned Barbadian singer, songwriter, actress, and businesswoman. She rose to fame after signing with Def Jam in 2005 and releasing her first two albums, \"Music of the Sun\" and \"A Girl Like Me\". Her third album, \"Good Girl Gone Bad\", solidified her status as a major music icon. Some of her other successful albums include \"Rated R\", \"Loud\", \"Talk That Talk\", and \"Unapologetic\", which was her first to reach number one on the Billboard 200. \n",
      "\n",
      "Rihanna has sold over 250 million records worldwide, making her one of the best-selling music artists of all time. She has received numerous awards, including nine Grammy Awards, 12 Billboard Music Awards, and 13 American Music Awards. She also holds six Guinness World Records. \n",
      "\n",
      "In addition to her music career, Rihanna has ventured into business, founding the cosmetics brand Fenty Beauty and the fashion house Fenty under LVMH. She has also acted in several films, including \"Battleship\", \"Home\", \"Valerian and the City of a Thousand Planets\", and \"Ocean's 8\". \n",
      "\n",
      "Rihanna is also known for her philanthropic work, particularly through her Believe Foundation and the Clara Lionel Foundation. As of 2023, she is the wealthiest female musician, with an estimated net worth of $1.4 billion.\n"
     ]
    }
   ],
   "source": [
    "# define top-level nodes and vector retrievers\n",
    "nodes = []\n",
    "vector_query_engines = {}\n",
    "vector_retrievers = {}\n",
    "\n",
    "for wiki_title in wiki_titles:\n",
    "    # build vector index\n",
    "    vector_index = VectorStoreIndex.from_documents(\n",
    "        [docs_dict[wiki_title]],\n",
    "        transformations=[splitter],\n",
    "        callback_manager=callback_manager,\n",
    "    )\n",
    "    # define query engines\n",
    "    vector_query_engine = vector_index.as_query_engine(llm=llm)\n",
    "    vector_query_engines[wiki_title] = vector_query_engine\n",
    "    vector_retrievers[wiki_title] = vector_index.as_retriever()\n",
    "\n",
    "    # save summaries\n",
    "    out_path = Path(\"summaries\") / f\"{wiki_title}.txt\"\n",
    "    if not out_path.exists():\n",
    "        # use LLM-generated summary\n",
    "        summary_index = SummaryIndex.from_documents(\n",
    "            [docs_dict[wiki_title]], callback_manager=callback_manager\n",
    "        )\n",
    "\n",
    "        summarizer = summary_index.as_query_engine(\n",
    "            response_mode=\"tree_summarize\", llm=llm\n",
    "        )\n",
    "        response = await summarizer.aquery(\n",
    "            f\"Give me a summary of {wiki_title}\"\n",
    "        )\n",
    "\n",
    "        wiki_summary = response.response\n",
    "        Path(\"summaries\").mkdir(exist_ok=True)\n",
    "        with open(out_path, \"w\") as fp:\n",
    "            fp.write(wiki_summary)\n",
    "    else:\n",
    "        with open(out_path, \"r\") as fp:\n",
    "            wiki_summary = fp.read()\n",
    "\n",
    "    print(f\"**Summary for {wiki_title}: {wiki_summary}\")\n",
    "    node = IndexNode(text=wiki_summary, index_id=wiki_title)\n",
    "    nodes.append(node)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3f10b9d-2cdc-44d7-9f2c-44c1438fad9e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "**********\n",
      "Trace: index_construction\n",
      "**********\n"
     ]
    }
   ],
   "source": [
    "# define top-level retriever\n",
    "top_vector_index = VectorStoreIndex(\n",
    "    nodes, transformations=[splitter], callback_manager=callback_manager\n",
    ")\n",
    "top_vector_retriever = top_vector_index.as_retriever(similarity_top_k=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65547fe1-6d2c-4658-8552-08a34f9c763f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# define recursive retriever\n",
    "from llama_index.core.retrievers import RecursiveRetriever\n",
    "from llama_index.core.query_engine import RetrieverQueryEngine\n",
    "from llama_index.core import get_response_synthesizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bfb2b340",
   "metadata": {},
   "outputs": [],
   "source": [
    "# note: can pass `agents` dict as `query_engine_dict` since every agent can be used as a query engine\n",
    "recursive_retriever = RecursiveRetriever(\n",
    "    \"vector\",\n",
    "    retriever_dict={\"vector\": top_vector_retriever, **vector_retrievers},\n",
    "    # query_engine_dict=vector_query_engines,\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3df4a090-c45a-4e3e-8d0a-f2955204bf26",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;34mRetrieving with query id None: Tell me about a celebrity from the United States\n",
      "\u001b[0mINFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "\u001b[1;3;38;5;200mRetrieved node with id, entering: Michael Jordan\n",
      "\u001b[0m\u001b[1;3;34mRetrieving with query id Michael Jordan: Tell me about a celebrity from the United States\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: In 1999, an ESPN survey of journalists, athletes and other sports figures ranked Jordan the greatest North American athlete of the 20th century. Jordan placed second to Babe Ruth in the Associated Press' December 1999 list of 20th century athletes. In addition, the Associated Press voted him the greatest basketball player of the 20th century. Jordan has also appeared on the front cover of Sports Illustrated a record 50 times. In the September 1996 issue of Sport, which was the publication's 50th-anniversary issue, Jordan was named the greatest athlete of the past 50 years.Jordan's athletic leaping ability, highlighted in his back-to-back Slam Dunk Contest championships in 1987 and 1988, is credited by many people with having influenced a generation of young players. Several NBA players, including James and Dwyane Wade, have stated that they considered Jordan their role model while they were growing up. In addition, commentators have dubbed a number of next-generation players \"the next Michael Jordan\" upon their entry to the NBA, including Penny Hardaway, Grant Hill, Allen Iverson, Bryant, Vince Carter, James, and Wade.\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: In 1999, he was named the 20th century's greatest North American athlete by ESPN and was second to Babe Ruth on the Associated Press' list of athletes of the century. Jordan was twice inducted into the Naismith Memorial Basketball Hall of Fame, once in 2009 for his individual career, and again in 2010 as part of the 1992 United States men's Olympic basketball team (\"The Dream Team\"). He became a member of the United States Olympic Hall of Fame in 2009, a member of the North Carolina Sports Hall of Fame in 2010, and an individual member of the FIBA Hall of Fame in 2015 and a \"Dream Team\" member in 2017. Jordan was named to the NBA 50th Anniversary Team in 1996 and to the NBA 75th Anniversary Team in 2021.One of the most effectively marketed athletes of his generation, Jordan made many product endorsements. He fueled the success of Nike's Air Jordan sneakers, which were introduced in 1984 and remain popular.\n",
      "\u001b[0mIn 1999, an ESPN survey of journalists, athletes and other sports figures ranked Jordan the greatest North American athlete of the 20th century. Jordan placed second to Babe Ruth in the Associated Press' December 1999 list of 20th century athletes. In addition, the Associated Press voted him the greatest basketball player of the 20th century. Jordan has also appeared on the front cover of Sports Illustrated a record 50 times. In the September 1996 issue of Sport, which was the publication's 50th-anniversary issue, Jordan was named the greatest athlete of the past 50 years.Jordan's athletic leaping ability, highlighted in his back-to-back Slam Dunk Contest championships in 1987 and 1988, is credited by many people with having influenced a generation of young players. Several NBA players, including James and Dwyane Wade, have stated that they considered Jordan their role model while they were growing up. In addition, commentators have dubbed a number of next-generation players \"the next Michael Jordan\" upon their entry to the NBA, including Penny Hardaway, Grant Hill, Allen Iverson, Bryant, Vince Carter, James, and Wade.\n",
      "In 1999, he was named the 20th century's greatest North American athlete by ESPN and was second to Babe Ruth on the Associated Press' list of athletes of the century. Jordan was twice inducted into the Naismith Memorial Basketball Hall of Fame, once in 2009 for his individual career, and again in 2010 as part of the 1992 United States men's Olympic basketball team (\"The Dream Team\"). He became a member of the United States Olympic Hall of Fame in 2009, a member of the North Carolina Sports Hall of Fame in 2010, and an individual member of the FIBA Hall of Fame in 2015 and a \"Dream Team\" member in 2017. Jordan was named to the NBA 50th Anniversary Team in 1996 and to the NBA 75th Anniversary Team in 2021.One of the most effectively marketed athletes of his generation, Jordan made many product endorsements. He fueled the success of Nike's Air Jordan sneakers, which were introduced in 1984 and remain popular.\n"
     ]
    }
   ],
   "source": [
    "# run recursive retriever\n",
    "nodes = recursive_retriever.retrieve(\n",
    "    \"Tell me about a celebrity from the United States\"\n",
    ")\n",
    "for node in nodes:\n",
    "    print(node.node.get_content())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f3a83e8-5872-4d55-9307-f4cd4c79216c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;34mRetrieving with query id None: Tell me about the childhood of a billionaire who started at company at the age of 16\n",
      "\u001b[0mINFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "\u001b[1;3;38;5;200mRetrieved node with id, entering: Richard Branson\n",
      "\u001b[0m\u001b[1;3;34mRetrieving with query id Richard Branson: Tell me about the childhood of a billionaire who started at company at the age of 16\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: He attended Stowe School, a private school in Buckinghamshire until the age of sixteen.Branson has dyslexia, and had poor academic performance; on his last day at school, his headmaster, Robert Drayson, told him he would either end up in prison or become a millionaire. \n",
      "Branson has also talked openly about having ADHD.\n",
      "Branson's parents were supportive of his endeavours from an early age. His mother was an entrepreneur; one of her most successful ventures was building and selling wooden tissue boxes and wastepaper bins. In London, he started off squatting from 1967 to 1968.Branson is an atheist. He said in a 2011 interview with CNN's Piers Morgan that he believes in evolution and the importance of humanitarian efforts but not in the existence of God. \"I would love to believe,\" he said. \"It's very comforting to believe\".\n",
      "\n",
      "\n",
      "== Early business career ==\n",
      "After failed attempts to grow and sell both Christmas trees and budgerigars, Branson launched a magazine named Student in 1966 with Nik Powell.\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: Later, he stated that one of his great-great-great-grandmothers was an Indian named Ariya.Branson was educated at Scaitcliffe School, a prep school in Surrey, before briefly attending Cliff View House School in Sussex. He attended Stowe School, a private school in Buckinghamshire until the age of sixteen.Branson has dyslexia, and had poor academic performance; on his last day at school, his headmaster, Robert Drayson, told him he would either end up in prison or become a millionaire. \n",
      "Branson has also talked openly about having ADHD.\n",
      "Branson's parents were supportive of his endeavours from an early age. His mother was an entrepreneur; one of her most successful ventures was building and selling wooden tissue boxes and wastepaper bins. In London, he started off squatting from 1967 to 1968.Branson is an atheist. He said in a 2011 interview with CNN's Piers Morgan that he believes in evolution and the importance of humanitarian efforts but not in the existence of God. \"I would love to believe,\" he said.\n",
      "\u001b[0mHe attended Stowe School, a private school in Buckinghamshire until the age of sixteen.Branson has dyslexia, and had poor academic performance; on his last day at school, his headmaster, Robert Drayson, told him he would either end up in prison or become a millionaire. \n",
      "Branson has also talked openly about having ADHD.\n",
      "Branson's parents were supportive of his endeavours from an early age. His mother was an entrepreneur; one of her most successful ventures was building and selling wooden tissue boxes and wastepaper bins. In London, he started off squatting from 1967 to 1968.Branson is an atheist. He said in a 2011 interview with CNN's Piers Morgan that he believes in evolution and the importance of humanitarian efforts but not in the existence of God. \"I would love to believe,\" he said. \"It's very comforting to believe\".\n",
      "\n",
      "\n",
      "== Early business career ==\n",
      "After failed attempts to grow and sell both Christmas trees and budgerigars, Branson launched a magazine named Student in 1966 with Nik Powell.\n",
      "Later, he stated that one of his great-great-great-grandmothers was an Indian named Ariya.Branson was educated at Scaitcliffe School, a prep school in Surrey, before briefly attending Cliff View House School in Sussex. He attended Stowe School, a private school in Buckinghamshire until the age of sixteen.Branson has dyslexia, and had poor academic performance; on his last day at school, his headmaster, Robert Drayson, told him he would either end up in prison or become a millionaire. \n",
      "Branson has also talked openly about having ADHD.\n",
      "Branson's parents were supportive of his endeavours from an early age. His mother was an entrepreneur; one of her most successful ventures was building and selling wooden tissue boxes and wastepaper bins. In London, he started off squatting from 1967 to 1968.Branson is an atheist. He said in a 2011 interview with CNN's Piers Morgan that he believes in evolution and the importance of humanitarian efforts but not in the existence of God. \"I would love to believe,\" he said.\n"
     ]
    }
   ],
   "source": [
    "nodes = recursive_retriever.retrieve(\n",
    "    \"Tell me about the childhood of a billionaire who started at company at\"\n",
    "    \" the age of 16\"\n",
    ")\n",
    "for node in nodes:\n",
    "    print(node.node.get_content())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_index_v2",
   "language": "python",
   "name": "llama_index_v2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
